package dosgi.web;

import java.io.File;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dosgi.Dosgi;
import com.dosgi.kit.PathKit;
import com.dosgi.kit.ValueKit;

/**
 * @author dingnate
 *
 */
public class DosgiFilter implements Filter {
	private static Logger LOG = LoggerFactory.getLogger(DosgiFilter.class);

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// 设置模块的打包及加载路径，重要！！！，否则无法加载模块
		String moduleHome = ValueKit.getValue(
				ValueKit.getValue(System.getProperty(Dosgi.MODULE_HOME_KEY),
						filterConfig.getInitParameter(Dosgi.MODULE_HOME_KEY)), "../modules");
		if (!PathKit.isAbsolutelyPath(moduleHome))
			try {
				moduleHome = new File(PathKit.getWebRootPath(), moduleHome).getCanonicalPath();
			} catch (IOException e) {
				//do nothing
			}
		Dosgi.start(moduleHome, false);
		try {
			Dosgi.getLifeCycle().waitForStarted();
			Dosgi.context().restartModule("dosgi.module.system", null);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
	}

	@Override
	public void destroy() {
	}
}
